package com.cxh.mediasessiondemo;

import android.content.ContentProviderClient;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaDescription;
import android.media.browse.MediaBrowser;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by Cxh
 * Time : 2021/10/23  00:24
 * Desc :
 */
public class MusicDataManager implements IMediaData {

    private final List<MediaBrowser.MediaItem> mMediaItems = new CopyOnWriteArrayList<>();
    private final Random mRandom = new Random();
    private Context mContext;
    private int mCurrentIndex;
    private int mLoopMode;

    public MusicDataManager(Context context) {
        mContext = context;
        mLoopMode = PLAY_TYPE_DEFAULT;
    }

    public void queryAudioList() {
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        ContentProviderClient providerClient = null;

        try {
            providerClient = mContext.getContentResolver().acquireUnstableContentProviderClient(uri);
            if (null != providerClient) {
                String[] projection = {
                        MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.DATA
                };

                String selection = null;
                String[] selectArgs = {null};
                if (Build.VERSION.SDK_INT >= 29) {
                    // 过滤小于1分钟的音乐
                    selection = MediaStore.Audio.Media.DURATION + ">?";
                    selectArgs[0] = "60000";
                }

                Cursor cursor = providerClient.query(uri, projection, selection, selectArgs,
                        MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
                if (null != cursor) {
                    while (cursor.moveToNext()) {
                        String id = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media._ID));
                        String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                        String author = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                        Uri audioUri = Uri.parse(uri.toString() + "/" + id);

                        Bundle bundle = new Bundle();
                        bundle.putString(KEY_MEDIA_ID, id);
                        bundle.putString(KEY_MEDIA_TITLE, title);
                        bundle.putString(KEY_MEDIA_AUTHOR, author);
                        bundle.putString(KEY_MEDIA_PATH, path);
                        MediaDescription description = new MediaDescription.Builder()
                                .setMediaId(id)
                                .setTitle(title)
                                .setSubtitle(author)
                                .setMediaUri(audioUri)
                                .setExtras(bundle)
                                .build();
                        MediaBrowser.MediaItem mediaItem = new MediaBrowser.MediaItem(description,
                                MediaBrowser.MediaItem.FLAG_PLAYABLE);
                        mMediaItems.add(mediaItem);
                    }
                    cursor.close();
                }
                providerClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.i("queryAudioList, error: " + e.toString());
        } finally {
            if (null != providerClient) {
                providerClient.close();
            }
        }
    }

    public MediaBrowser.MediaItem selectMediaFromMediaId(String mediaId) {
        if (TextUtils.isEmpty(mediaId)) {
            return null;
        }

        for (int i = 0; i < mMediaItems.size(); i++) {
            if (mediaId.equals(mMediaItems.get(i).getMediaId())) {
                mCurrentIndex = i;
                return mMediaItems.get(i);
            }
        }

        return null;
    }

    public MediaBrowser.MediaItem changeToNext() {
        switch (mLoopMode) {
            case PLAY_TYPE_SINGLE:
            case PLAY_TYPE_RANDOM:
                mRandom.setSeed(System.currentTimeMillis());
                mCurrentIndex = mRandom.nextInt(mMediaItems.size());
                break;
            default: {
                mCurrentIndex++;
                if (mCurrentIndex >= mMediaItems.size()) {
                    mCurrentIndex = 0;
                }
            }
            break;
        }

        return mMediaItems.get(mCurrentIndex);
    }

    public MediaBrowser.MediaItem changeToPrevious() {
        switch (mLoopMode) {
            case PLAY_TYPE_SINGLE:
            case PLAY_TYPE_RANDOM:
                mRandom.setSeed(System.currentTimeMillis());
                mCurrentIndex = mRandom.nextInt(mMediaItems.size());
                break;
            default: {
                mCurrentIndex--;
                if (mCurrentIndex < 0) {
                    mCurrentIndex = mMediaItems.size() - 1;
                }
            }
            break;
        }

        return mMediaItems.get(mCurrentIndex);
    }

    public int changeLoopMode() {
        switch (mLoopMode) {
            case PLAY_TYPE_SINGLE:
                mLoopMode = PLAY_TYPE_DEFAULT;
                break;
            case PLAY_TYPE_RANDOM:
                mLoopMode = PLAY_TYPE_SINGLE;
                break;
            case PLAY_TYPE_DEFAULT:
                mLoopMode = PLAY_TYPE_RANDOM;
                break;
            default:
                mLoopMode = PLAY_TYPE_DEFAULT;
                break;
        }
        return mLoopMode;
    }

    public void setCurrentIndex(int currentIndex) {
        mCurrentIndex = currentIndex;
    }

    public int getCurrentIndex() {
        return mCurrentIndex;
    }

    public List<MediaBrowser.MediaItem> getMediaItems() {
        return mMediaItems;
    }

    public int getLoopMode() {
        return mLoopMode;
    }

    public MediaBrowser.MediaItem getCurrentItem() {
        return mMediaItems.get(mCurrentIndex);
    }
}
